<?php
// 检查用户是否登录
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('HTTP/1.1 401 Unauthorized');
    exit;
}

// 检查是否有文件上传
if (empty($_FILES['file'])) {
    echo json_encode(['error' => 'No file uploaded.']);
    exit;
}

$file = $_FILES['file'];

// 检查上传错误
if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['error' => 'Upload error: ' . $file['error']]);
    exit;
}

// 检查文件类型（仅允许图片）
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($file['type'], $allowed_types)) {
    echo json_encode(['error' => 'Invalid file type. Only JPEG, PNG, GIF, WebP are allowed.']);
    exit;
}

// 检查文件大小 (例如，最大 5MB)
// if ($file['size'] > 5 * 1024 * 1024) { // 5MB
//     echo json_encode(['error' => 'File size exceeds limit (5MB).']);
//     exit;
// }

// 为文件生成唯一名称，防止冲突
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$new_filename = uniqid() . '.' . $extension;
$upload_dir = __DIR__ . '/uploads/';
$upload_path = $upload_dir . $new_filename;

// 确保上传目录存在且可写
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// 移动上传的文件
if (move_uploaded_file($file['tmp_name'], $upload_path)) {
    // 构建图片的URL，返回给TinyMCE
    $image_url = 'uploads/' . $new_filename; // 相对于网站根目录的路径
    echo json_encode(['location' => $image_url]);
} else {
    echo json_encode(['error' => 'Failed to move uploaded file.']);
}
?> 